<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>叠加轮播</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        text-decoration: none;
        list-style: none;
      }
      #carousel {
        width: 800px;
        height: 400px;
        margin: 20px auto;
        position: relative;
      }
      #carousel img {
        width: 100%;
        height: 100%;
        display: block;
        position: absolute;
        left: 0;
        top: 0;
        /* 为img的opacity添加过渡动画 */
        transition: opacity 1s linear;
      }
    </style>
  </head>
  <body>
    <ul id="carousel">
        <li>
          <a href="#"><img src="images/1.jpg" alt="banner" /></a>
        </li>
        <li>
          <a href="#"><img src="images/2.jpg" alt="banner" /></a>
        </li>
        <li>
          <a href="#"><img src="images/3.jpg" alt="banner" /></a>
        </li>
        <li>
          <a href="#"><img src="images/4.jpg" alt="banner" /></a>
        </li>
      </ul>
  </body>
  <script>
    var carousel = document.getElementById("carousel");
    var imgs = document.getElementsByTagName("img");
    var timer = null;
    var idx = 0;

    function animation() {
      if (idx >= imgs.length - 1) {
        idx = 0; //如果到了最后一张图将重新回到第一张图，从而实现循环
      } else {
        idx++;
      }
      // console.log(idx);
      // 当idx的值发生改变时，显示下标为idx的这张图，其它图隐藏
      // 通过修改不透明度/display/[show,fadeIn JQ]写法实现
      for (var i = 0, len = imgs.length; i < len; i++) {
        if (i === idx) {
          imgs[i].style.cssText = "opacity:1;filter:alpha(opacity=100)";
          // "opacity:1;filter:alpha(opacity=100)" 兼容写法
          // imgs[i].style.display ="none";
          // imgs[i].fadeIn(200);JQ写法，原生不支持
        } else {
          imgs[i].style.cssText = "opacity:0;filter:alpha(opacity=0)";
          // imgs[i].style.display ="block";
          // imgs[i].fadeOut(200);
        }
      }
    }

    timer = setInterval(animation, 3000);
    // 参数animation相当于将animation函数内容放在原来的回调函数的位置充当其回调函数，
    // 若写animation()则相当于立即执行animation函数.
    //计时器中的变量相当于静态变量(函数执行完后变量不会立即从内存中销毁，仍会驻留内存一段时间)

    carousel.onmouseover = function () {
      clearInterval(timer);
    };
    carousel.onmouseout = function () {
      timer = setInterval(animation, 3000);
    };
  </script>
</html>
